package example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*") // 拦截所有请求路径
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作，可以在这里获取过滤器的初始化参数等
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String requestURI = request.getRequestURI();

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            // 登录页面或静态资源直接放行
            if (requestURI.contains("login.jsp") || requestURI.contains("login") || requestURI.contains("/") || requestURI.endsWith(".css") || requestURI.endsWith(".js")) {
                filterChain.doFilter(request, response);
            } else {
                // 验证用户是否已登录
                if (session != null && session.getAttribute("user") != null) {
                    // 用户已登录，放行请求
                    filterChain.doFilter(request, response);
                } else {
                    // 用户未登录，重定向到登录页面
                    response.sendRedirect("login.jsp");
                }
            }
        } catch (Exception e) {
            // 捕获异常并处理
            e.printStackTrace(); // 打印异常日志（可选）

            // 将错误信息存入请求作用域
            request.setAttribute("errorMessage", e.getMessage());

            // 转发到统一的错误页面
            request.getRequestDispatcher("500.jsp").forward(request, response);
        }
    }

    @Override
    public void destroy() {
        // 销毁资源，例如关闭数据库连接等（如果在过滤器中有相关资源的话）
    }
}
